/*********************
* Author:Dzlua
* QQ:505544956
* time:2016/11/08
*/
#include "Link.h"
#include "../edui.h"

EDUI_NAMESPACE_BEGIN

Link* Link::GetInterface()
{
    Link* link = new Link;
#ifdef EDUI_TEST_NEW_DELETE
    ++m_newdeleteNum;
    Log("[Link] new link : %d", link);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Add("Link", link);
#endif
    return link;
}

void Link::Release()
{
#ifdef EDUI_TEST_NEW_DELETE
    --m_newdeleteNum;
    Log("[Link] delete link : %s, %d", this->GetName(), this);
#endif
#ifdef EDUI_USE_LUAPLUS
    LuaMgrPtr->Remove(this);
#endif
    delete this;
}

Link* Link::ToLink(Control* ctrl)
{
    return dynamic_cast<Link*>(ctrl);
}

Link::Link() : m_bUnderLine(false)
{
    m_bDragWnd = false;
}

Link::~Link()
{}

bool Link::HandleMsg(Msg* msg)
{
    if (msg->msg == MSG_MOUSE_BUTTON_DOWN){
        MouseButtonMsg *evt = &msg->button;
        if (m_rc.IsInRect(evt->x, evt->y)){
            this->DoEvent(EVENT_CLICK);
            return true;
        }
    } 
    return Control::HandleMsg(msg);
}

void Link::RenderText(IRender* render, const Rect* renderrc)
{
    if (m_text.IsEmpty()) return;

    //get text
    const char* text = this->GetTranslateText();
    if (!text) return;

    //get font
    IFont* font = this->GetFont();
    if (!font) return;

    int style = font->GetStyle();
    
    if (m_bUnderLine) font->SetStyle(style | FONT_STYLE_UNDERLINE);
    else font->SetStyle(style &~ FONT_STYLE_UNDERLINE);

    //render
    Size sz = font->GetSizeUTF8(text);
    Rect rc = this->GetTextAlignRect(&sz);
    render->DrawText(text, &rc, font, &m_textColor);

    font->SetStyle(style);
}

void Link::DoEvent(EventType type, void* data1, void* data2)
{
    switch (type){
        case EVENT_CLICK : this->evt.click.emit(this); break;
    }
#ifdef EDUI_USE_LUAPLUS
    switch (type){
        case EVENT_CLICK : LuaMgrPtr->DoEvent(this, "click"); break;
    }
#endif
}

void Link::OnMouseIn()
{
    Label::OnMouseIn();
    m_bUnderLine = true;
    this->Invaldate();
}

void Link::OnMouseOut()
{
    Label::OnMouseOut();
    m_bUnderLine = false;
    this->Invaldate();
}

EDUI_NAMESPACE_END
